<template>
  <div class="mobile-video-page bg-white min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="left-section">
        <div class="logo">
          <img src="../../../assets/images/logo.png" alt="logo" class="logo">
        </div>
        <div class="title-container">
          <div class="title">西大数信数帮学堂</div>
          <div class="sub-title">广西大学数学与信息科学学院</div>
        </div>
      </div>
      <div class="search-box">
        <div class="search-box">
          <el-input
              v-model="searchKeyword"
              placeholder="输入关键词搜索"
              class="search-input"
              size="small"
              clearable
              @keydown="handleSearchKeydown"
              @keyup.enter="performSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <div class="home-btn">
        <button class="home-button" @click="goHome">首页</button>
      </div>
    </header>

    <!-- 视频播放器区域 -->
    <div class="video-container relative bg-black">
      <div class="video-player aspect-video bg-black relative">
        <!-- 真实视频播放器 -->
        <div class="video-page">
          <Async :loading="loading" :error="error" :empty="nodata" empty-text="没有找到视频" >
            <main>
              <video-page-left/>
            </main>
          </Async>
        </div>

        <!-- 视频信息叠加层（仅在需要时显示） -->
<!--        <div class="video-overlay absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-4 opacity-0 hover:opacity-100 transition-opacity duration-300">
          <div class="text-white">
            <div class="flex items-center justify-between mb-2">
              <span class="text-sm">05:34 / 05:34</span>
              <div class="flex items-center space-x-2">
                <span class="text-xs bg-black/50 px-2 py-1 rounded">1 人正在看</span>
              </div>
            </div>
          </div>
        </div>-->
      </div>
    </div>

    <!-- 视频信息区域 -->
    <div class="video-info bg-white px-4 py-3"  v-if="videoStore.video">
      <!-- 顶部信息行：播放量、评论数、时间、观看人数 -->
      <div class="info-top flex items-center justify-between mb-3 text-sm text-gray-500">
        <div class="left-info flex items-center space-x-4">
          <span class="flex items-center" >
            <el-icon class="mr-1"><VideoPlay /></el-icon>
            {{ videoStore.video.plays }}
          </span>
<!--          <span class="flex items-center">
            <el-icon class="mr-1"><ChatDotRound /></el-icon>
            0
          </span>-->
          <span>{{ videoStore.video.createTime }}</span>
        </div>
        <div class="right-info">
          {{ watching }} 人正在看
        </div>
      </div>

      <!-- 视频标题 -->
      <h1 class="video-title text-base font-semibold mb-4 leading-tight text-gray-900">

        {{ videoStore.video.title }}
      </h1>

      <!-- 底部互动按钮 -->
      <div class="video-title text-base font-semibold mb-4 leading-tight ">
        <rich-text :content="videoStore.video.intro" html />
<!--        &lt;!&ndash; 点赞 &ndash;&gt;
        <div class="action-item flex items-center cursor-pointer">
          <el-icon class="mr-1 text-gray-600"><GoodsFilled /></el-icon>
          <span class="text-sm text-gray-600">0</span>
        </div>

        &lt;!&ndash; 投币 &ndash;&gt;
        <div class="action-item flex items-center cursor-pointer">
          <el-icon class="mr-1 text-gray-600"><Coin /></el-icon>
          <span class="text-sm text-gray-600">0</span>
        </div>

        &lt;!&ndash; 收藏 &ndash;&gt;
        <div class="action-item flex items-center cursor-pointer">
          <el-icon class="mr-1 text-gray-600"><StarFilled /></el-icon>
          <span class="text-sm text-gray-600">0</span>
        </div>

        &lt;!&ndash; 分享 &ndash;&gt;
        <div class="action-item flex items-center cursor-pointer">
          <el-icon class="mr-1 text-gray-600"><Share /></el-icon>
          <span class="text-sm text-gray-600">0</span>
        </div>-->
      </div>
    </div>

    <!-- 相关推荐区域 -->
    <div class="recommendations bg-gray-50 px-4 py-4">
      <h2 class="section-title text-lg font-medium mb-4">相关推荐</h2>

      <div class="recommendation-list space-y-4">
        <!-- 推荐视频项 -->
        <div class="recommendation-item flex bg-white rounded-lg overflow-hidden shadow-sm" v-for="item in state" :key="item.id">
          <div class="video-thumb relative flex-shrink-0"  @click="goToVideo(item)">
            <img :src="getImageUrl(item.bannerId)" alt="视频缩略图" class="w-32 h-20 object-cover bg-gray-200" />
            <div class="duration absolute bottom-1 right-1 bg-black/70 text-white text-xs px-1 rounded">
              {{ displayDuration(item?.duration ?? 0*1000) }}
            </div>
            <div class="play-icon absolute inset-0 flex items-center justify-center">
              <svg class="w-8 h-8 text-white/80" fill="currentColor" viewBox="0 0 24 24">
                <path d="M8 5v14l11-7z"/>
              </svg>
            </div>
          </div>

          <div class="video-info flex-1 p-3" @click="goToVideo(item)">
            <h3 class="video-title text-sm font-medium leading-tight mb-2 line-clamp-2">
              {{ item.title }}
            </h3>
            <div class="video-meta text-xs text-gray-500 space-y-1">
              <div class="flex items-center">
                <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M8 5v14l11-7z"/>
                  <circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="1"/>
                </svg>
                <span> {{ item.plays }}</span>
<!--                <svg class="w-3 h-3 ml-3 mr-1" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M9 11H7v6h2v-6zm4 0h-2v6h2v-6zm4 0h-2v6h2v-6zm2-7H3v2h2v13a1 1 0 001 1h12a1 1 0 001-1V6h2V4zM6 6h12v13H6V6z"/>
                </svg>
                <span>0</span>-->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import VideoPageLeft from './left/index.vue';
import { ref, onMounted } from 'vue'
import { GoodsFilled, Coin, StarFilled, Share, Search, VideoPlay, ChatDotRound } from '@element-plus/icons-vue'

import { useVideoStore } from '@/stores/video';
import videoApi from '@/apis/video';
import { isInteger, toInteger } from 'lodash';
import videoOnlineApi from "@/apis/video/online"
import VideoPageRight from "@/pages/video/right/index.vue";
import { imageUrl } from '@/apis/image';
import {displayDuration} from "@/utils/common.ts";
import {useRouter} from "vue-router";


const videoStore = useVideoStore()
const route = useRoute()
const router = useRouter()
//id或sid
const sid = useRouteParams<string>('sid')
//第多少P
const part = useRouteParams<number>('part', 1, { transform: toInteger })
const share = useRouteQuery<string>('share')
const loading = ref(true)
const error = ref(null)
const nodata = ref(false)
const watching = ref(1)



// 获取图片URL
function getImageUrl(bannerId: string) {
  // 根据您的实际API调整图片URL构造方式
  // return `/api/resource/${bannerId}`
  return imageUrl + bannerId
}

//当检测到url的视频id变化后重新获取视频信息
watchImmediate(sid, async (newId)=>{
  if (!sid.value || sid.value==videoStore.video?.sid) {
    return
  }
  loading.value = true
  try {
    videoStore.video = null
    const video = await videoApi.getById(sid.value)
    //如果请求完成前又变更了id,则放弃结果
    if (newId !== sid.value) {
      return
    }
    if (!video || video.canplayCount === 0) {
      nodata.value = true
      return
    }
    videoStore.video = video
    document.title = video.title + ' - 数帮学堂'
    if (share.value) {
      videoApi.useShare(share.value)
    }
    //如果当前不是用的短id,则更换为短id
    if (video.sid != sid.value) {
      sid.value = video.sid
    }
    //寻找sort最低的能播放的视频
    if (!isInteger(route.params?.part)) {
      const first = video.parts.find(a=>a.canplay)
      if (first && first.sort !== 1) {
        part.value = first.sort
      }
    }
  } catch(err) {
    error.value = err
  } finally {
    loading.value = false
  }
})
watchImmediate(part, ()=>{
  videoStore.partNumber = part.value
})

//刷新当前观看人数
function refreshWatchCount() {
  if (videoStore.video) {
    videoOnlineApi.getOnline(videoStore.video.id).then(val=>{
      watching.value = Math.max(1, val)
    })
  }
}


// 添加时间记录
const courseTimes = ref<Record<string, number>>({})
// 修改时间更新函数
const onTimeUpdate = (time: number, value: { sid: string }) => {
  courseTimes.value[value.sid] = time
}
//点击视频
const  goToVideo = (value: Object) => {

  const url = generateVideoUrl(value)
  // 使用 Vue Router 在当前页面跳转
  router.push(url)
}
// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/mobile/play/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0

  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}

//定时刷新当前观看人数
useIntervalFn(refreshWatchCount, 30_000, { immediate: true })

//推荐的关联视频列表
const { state, execute } = useAsyncState(
  () => videoApi.getRelatedList(videoStore?.video?.id ?? 0),
  []
)
//检测到切换视频后重新推荐视频
watch(()=>videoStore.video, ()=>execute())

// 响应式数据
const isPlaying = ref(false)

// 播放/暂停控制
const togglePlay = () => {
  isPlaying.value = !isPlaying.value
}

// 格式化时间
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 搜索关键词
const searchKeyword = ref('')
const tipIndex = ref(-1)
const tipList = ref([])
const currentSlideIndex = ref(0);

// 添加键盘事件处理
function handleSearchKeydown(e: KeyboardEvent) {
  let offset = 0
  if (e.code === 'ArrowUp') {
    offset = -1
  } else if (e.code === 'ArrowDown') {
    offset = 1
  }

  if (offset) {
    e.preventDefault()
    const newIndex = tipIndex.value + offset
    if (newIndex >= tipList.value.length) {
      tipIndex.value = -1
    } else if(newIndex < -1) {
      tipIndex.value = tipList.value.length - 1
    } else {
      tipIndex.value = newIndex
    }
  }
}

// 执行搜索功能
function performSearch() {
  console.log('测试的辞keyword:', searchKeyword.value)
  // 检查是否已经在mobileSearch页面并且参数相同
  if (route.name === 'mobileSearch' && route.query.kw === searchKeyword.value) {
    console.log('Already on the same search page with same query')
    return
  }

  // 在这里添加实际的搜索逻辑
  router.push(`/mobileSearch?kw=${encodeURIComponent(searchKeyword.value)}`)
}

// 返回上一页
const goBack = () => {
  // 这里可以添加路由返回逻辑
  console.log('返回上一页')
}

// 跳转首页
const goHome = () => {
  // 这里可以添加跳转首页逻辑
  const router = useRouter()
  router.push("/mobile")
}

onMounted(() => {
  // 页面加载完成后的初始化逻辑
  console.log('移动端视频页面加载完成')
})
</script>

<style scoped>
.mobile-video-page {
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.video-container {
  position: relative;
}

.video-player {
  width: 100%;
  background: #000;
}

.math-content {
  font-family: 'Times New Roman', serif;
  line-height: 1.6;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.progress-bar {
  position: relative;
  cursor: pointer;
}

.progress {
  transition: width 0.3s ease;
}

.video-thumb {
  position: relative;
  width: 128px;
  height: 80px;
}

.play-icon {
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

.recommendation-item:hover .play-icon {
  opacity: 1;
}

/* 顶部导航栏样式 */
.header {
  display: flex;
  align-items: center;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)),
              url('@/assets/1sz3p8w2Sk.png@3840w_400h_1c.webp');
  background-size: cover;
  background-position: center;
  backdrop-filter: blur(2px);
  padding: 6px 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 999;
  gap: 6px;
  width: 100%;
  box-sizing: border-box;
}

.left-section {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo {
  flex-shrink: 0;
}

.logo img {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  object-fit: cover;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title-container {
  flex: 1;
  min-width: 0;
}

.title {
  font-size: 13px;
  font-weight: 600;
  line-height: 1.2;
  color: #222;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 1px;
}

.sub-title {
  font-size: 9px;
  color: #666;
  line-height: 1.1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-input {
  width: 160px;
  max-width: 100%;
}

.search-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  padding: 4px 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-wrapper:focus-within {
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: scale(1.02);
}

.search-icon {
  font-size: 14px;
  color: #999;
  margin-right: 6px;
  flex-shrink: 0;
}

.search-wrapper input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  font-size: 11px;
  color: #333;
  padding: 0;
}

.search-wrapper input::placeholder {
  color: #999;
  font-size: 11px;
}

.home-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.home-button {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  padding: 4px 12px;
  font-size: 11px;
  font-weight: 500;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.home-button:hover {
  background: #ffffff;
  border-color: rgba(255, 255, 255, 0.5);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.home-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 视频容器样式 */
.video-container {
  position: relative;
  z-index: 1;
}

.video-overlay {
  pointer-events: none;
}

.video-overlay > * {
  pointer-events: auto;
}

/* 视频信息区域样式 */
.video-info {
  position: relative;
  z-index: 2;
  background: white;
}

.info-top .el-icon {
  font-size: 14px;
}

.action-item {
  transition: all 0.2s ease;
}

.action-item:hover {
  transform: translateY(-1px);
}

.action-item .el-icon {
  font-size: 18px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .header {
    padding: 5px 8px;
    gap: 6px;
  }

  .left-section {
    gap: 6px;
  }

  .logo img {
    width: 28px;
    height: 28px;
  }

  .title {
    font-size: 12px;
  }

  .sub-title {
    font-size: 8px;
  }

  .search-input {
    width: 140px;
  }

  .search-wrapper {
    padding: 3px 10px;
  }

  .search-wrapper input {
    font-size: 10px;
  }

  .home-btn {
    margin-left: 6px;
  }

  .home-button {
    padding: 3px 10px;
    font-size: 10px;
  }

  .video-title {
    font-size: 15px;
    line-height: 1.4;
  }

  .video-stats {
    padding: 12px 0;
  }

  .stat-item {
    margin-right: 16px;
  }

  .recommendation-item {
    margin-bottom: 12px;
  }

  .video-thumb {
    width: 120px;
    height: 75px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .header {
    padding: 4px 6px;
    gap: 4px;
  }

  .left-section {
    gap: 4px;
  }

  .logo img {
    width: 24px;
    height: 24px;
  }

  .title {
    font-size: 11px;
  }

  .sub-title {
    font-size: 7px;
  }

  .search-box {
    flex: 0 0 120px;
  }

  .search-wrapper {
    padding: 2px 8px;
  }

  .search-icon {
    font-size: 12px;
    margin-right: 4px;
  }

  .search-wrapper input {
    font-size: 9px;
  }

  .home-btn {
    margin-left: 4px;
  }

  .home-button {
    padding: 2px 8px;
    font-size: 9px;
    border-radius: 10px;
  }

  .video-title {
    font-size: 15px;
  }

  .video-thumb {
    width: 100px;
    height: 60px;
  }

  .video-info {
    padding: 8px;
  }
}
.search-input {
  width: 100%;

  :deep(.el-input__wrapper) {
    border-radius: 15px;
    background-color: #ffffff;
    box-shadow: none;
    padding: 2px 8px;
    min-height: 26px;
  }

  :deep(.el-input__inner) {
    font-size: 10px;
    color: #666;

    &::placeholder {
      color: #999;
    }
  }

  :deep(.el-input__prefix) {
    color: #999;
    font-size: 11px;
    margin-right: 4px;
  }
}
</style>
